// Kokomi.js - Three.js 组件框架
import * as kokomi from "kokomi.js";
// Three.js - 3D 渲染引擎
import * as THREE from "three";
// GSAP - 动画库
import gsap from "gsap";
// Howler - 音频播放库
import { Howl } from "howler";

import type Experience from "../Experience";

// 导入各种世界组件
import TestObject from "./TestObject"; // 测试对象（未使用）
import DynamicEnv from "./DynamicEnv"; // 动态环境
import StartRoom from "./StartRoom"; // 起始房间
import Car from "./Car"; // 汽车模型
import Speedup from "./Speedup"; // 加速特效
import CameraShake from "./CameraShake"; // 相机抖动
import Furina from "./Furina"; // 芙宁娜角色
import ColorPicker from "./ColorPicker"; // 颜色选择器
import CarTitle from "./CarTitle"; // 车辆标题
import CarTimeline from "./CarTimeline"; // 车辆时间线
import CarDimensions from "./CarDimensions"; // 车身尺寸标注
import CarWaveLines from "./CarWaveLines"; // 车身波浪线动画
import AirflowLines from "./AirflowLines"; // 风阻线条
import RadarAnimation from "./RadarAnimation"; // 雷达动画

/**
 * 世界场景组件
 * 管理所有场景对象（车、房间、特效等）
 * 控制所有动画序列（入场、加速、减速）
 */
export default class World extends kokomi.Component {
  declare base: Experience; // Experience 实例引用
  
  // ==================== 场景组件 ====================
  testObject: TestObject | null; // 测试对象（未启用）
  dynamicEnv!: DynamicEnv; // 动态环境贴图
  startRoom!: StartRoom; // 起始房间
  car!: Car; // 汽车模型
  furina!: Furina; // 芙宁娜角色（可选）
  speedup!: Speedup; // 加速特效
  environment!: kokomi.Environment; // 环境光
  cameraShake!: CameraShake; // 相机抖动
  colorPicker!: ColorPicker; // 颜色选择器
  carTitle!: CarTitle; // 车辆标题
  carTimeline!: CarTimeline; // 车辆时间线
  carDimensions!: CarDimensions; // 车身尺寸标注
  carWaveLines!: CarWaveLines; // 车身波浪线动画
  airflowLines: AirflowLines | null = null; // 风阻线条（仅在风阻视图时创建）
  radarAnimation: RadarAnimation | null = null; // 雷达动画（仅在雷达视图时创建）
  rotationGroup!: THREE.Group; // 旋转组（包含车子、地面、灯光板）
  carRotationTween: gsap.core.Tween | null = null; // 车辆旋转动画
  bgm!: Howl; // 背景音乐
  isRadarPressed: boolean = false; // 雷达视图是否按下
  
  // ==================== GSAP 动画时间轴 ====================
  // 每个时间轴控制一组相关动画
  t1!: ReturnType<typeof gsap.timeline>; // 相机位置动画
  t2!: ReturnType<typeof gsap.timeline>; // 灯光亮度动画
  t3!: ReturnType<typeof gsap.timeline>; // 环境光动画
  t4!: ReturnType<typeof gsap.timeline>; // 速度动画
  t5!: ReturnType<typeof gsap.timeline>; // 灯光透明度动画
  t6!: ReturnType<typeof gsap.timeline>; // 地板/芙宁娜颜色动画
  t7!: ReturnType<typeof gsap.timeline>; // 环境光强度动画
  t8!: ReturnType<typeof gsap.timeline>; // 加速特效/相机 FOV 动画
  t9!: ReturnType<typeof gsap.timeline>; // 车身/相机抖动/Bloom 动画
  constructor(base: Experience) {
    super(base);

    // 测试对象未启用
    this.testObject = null;

    // 监听资源加载完成事件
    this.base.am.on("ready", () => {
      // 处理加载完成的资源
      this.handleAssets();

      // 测试对象（已禁用）
      // this.testObject = new TestObject(this.base);
      // this.testObject.addExisting();

      // ==================== 初始化所有 GSAP 时间轴 ====================
      const t1 = gsap.timeline();
      this.t1 = t1;
      const t2 = gsap.timeline();
      this.t2 = t2;
      const t3 = gsap.timeline();
      this.t3 = t3;
      const t4 = gsap.timeline();
      this.t4 = t4;
      const t5 = gsap.timeline();
      this.t5 = t5;
      const t6 = gsap.timeline();
      this.t6 = t6;
      const t7 = gsap.timeline();
      this.t7 = t7;
      const t8 = gsap.timeline();
      this.t8 = t8;
      const t9 = gsap.timeline();
      this.t9 = t9;

      // 设置场景背景为黑色
      this.base.scene.background = new THREE.Color("black");

      // ==================== 创建动态环境 ====================
      // 从 HDR 纹理创建环境贴图 1（夜间）
      const envmap1 = kokomi.getEnvmapFromHDRTexture(
        this.base.renderer,
        this.base.am.items["ut_env_night"]
      );
      // 从 HDR 纹理创建环境贴图 2（明亮）
      const envmap2 = kokomi.getEnvmapFromHDRTexture(
        this.base.renderer,
        this.base.am.items["ut_env_light"]
      );
      // 创建动态环境组件，用于混合两个环境贴图
      const dynamicEnv = new DynamicEnv(this.base, {
        envmap1,
        envmap2,
      });
      this.dynamicEnv = dynamicEnv;
      // 将混合后的环境贴图设置为场景环境光
      this.base.scene.environment = dynamicEnv.envmap;
      dynamicEnv.setWeight(1); // 设置初始权重为 1
      // dynamicEnv.lerpWeight(1, 4); // 可选：平滑过渡

      // ==================== 创建场景对象 ====================
      // 创建旋转组（将车子、地面、灯光板作为整体）
      const rotationGroup = new THREE.Group();
      this.rotationGroup = rotationGroup;
      this.base.scene.add(rotationGroup);

      // 创建起始房间
      const startRoom = new StartRoom(this.base);
      this.startRoom = startRoom;
      startRoom.addExisting();

      // 创建汽车模型
      const car = new Car(this.base);
      this.car = car;
      car.addExisting();

      // 将车子、地面、灯光板移动到旋转组中
      rotationGroup.add(car.model.scene);
      rotationGroup.add(startRoom.reflecFloor);
      rotationGroup.add(startRoom.lightBoard);
      
      // 创建颜色选择器
      const colorPicker = new ColorPicker(this.base, car);
      this.colorPicker = colorPicker;
      
      // 创建车辆标题
      const carTitle = new CarTitle(this.base);
      this.carTitle = carTitle;
      
      // 创建车辆时间线
      const carTimeline = new CarTimeline(this.base);
      this.carTimeline = carTimeline;

      // 如果启用芙宁娜模式，创建芙宁娜角色
      if (this.base.params.isFurina) {
        const furina = new Furina(this.base);
        this.furina = furina;
        furina.addExisting();
      }

      // 创建加速特效
      const speedup = new Speedup(this.base);
      this.speedup = speedup;
      speedup.addExisting();

      // 创建车身尺寸标注
      const carDimensions = new CarDimensions(this.base);
      this.carDimensions = carDimensions;
      carDimensions.addExisting();

      // 创建车身波浪线动画
      const carWaveLines = new CarWaveLines(this.base);
      this.carWaveLines = carWaveLines;
      carWaveLines.addExisting();

      // 风阻线条在风阻视图时动态创建

      // ==================== 创建环境光组件 ====================
      // 用于加速时生成动态环境反射
      const environment = new kokomi.Environment(this.base, {
        resolution: 512, // 环境贴图分辨率
        scene: this.base.scene, // 目标场景
        options: {
          minFilter: THREE.LinearMipMapLinearFilter, // Mipmap 过滤
          anisotropy: 0, // 各向异性过滤
          depthBuffer: false, // 禁用深度缓冲
          generateMipmaps: true, // 生成 Mipmap
        },
        textureType: THREE.UnsignedByteType, // 纹理类型
        ignoreObjects: [this.car.model.scene], // 忽略车身（不参与环境反射）
      });
      this.environment = environment;

      // ==================== 创建相机抖动组件 ====================
      const cameraShake = new CameraShake(this.base);
      this.cameraShake = cameraShake;
      cameraShake.setIntensity(0); // 初始时无抖动

      // ==================== 设置交互 ====================
      // 将车添加到交互管理器（可点击）
      this.base.interactionManager.add(car.model.scene);
      // 点击车时触发加速
      car.model.scene.addEventListener("click", () => {
        this.rush();
      });

      // 按下车身触发波浪线动画，松开停止
      car.model.scene.addEventListener("pointerdown", () => {
        // 只在车身视图时才响应
        if (this.carTimeline.activeIndex !== 1) return;
        
        // 立即开始动画
        this.carWaveLines.start();
      });
      
      car.model.scene.addEventListener("pointerup", () => {
        // 松开鼠标立即停止动画
        this.carWaveLines.stop();
      });
      
      car.model.scene.addEventListener("pointerleave", () => {
        // 鼠标离开也停止动画
        this.carWaveLines.stop();
      });

      // 监听入场动画完成事件
      this.on("enter", () => {
        this.base.params.disableInteract = false; // 启用交互
        this.carTitle.show(); // 显示车辆标题
        this.carTimeline.show(); // 显示车辆时间线
      });

      // 监听时间线切换事件
      window.addEventListener("timeline-change", ((event: CustomEvent) => {
        const { item } = event.detail;
        this.handleTimelineChange(item.id);
      }) as EventListener);

      // 执行入场动画
      this.enter();
      // this.enterDirectly(); // 可选：直接进入（跳过动画）

      // ==================== 播放背景音乐 ====================
      this.bgm = new Howl({
        src: "audio/bgm.mp3", // 音频文件路径
        loop: true, // 循环播放
      });
      this.bgm.play(); // 开始播放
      
      // 创建音乐控制按钮
      this.createMusicControl();
    });
  }
  /**
   * 处理加载完成的资源
   * 配置贴图的各种属性
   */
  handleAssets() {
    const items = this.base.am.items;
    (items["ut_car_body_ao"] as THREE.Texture).flipY = false;
    (items["ut_car_body_ao"] as THREE.Texture).colorSpace =
      THREE.LinearSRGBColorSpace;
    (items["ut_car_body_ao"] as THREE.Texture).minFilter = THREE.NearestFilter;
    (items["ut_car_body_ao"] as THREE.Texture).magFilter = THREE.NearestFilter;
    (items["ut_car_body_ao"] as THREE.Texture).channel = 1;
    (items["ut_startroom_ao"] as THREE.Texture).flipY = false;
    (items["ut_startroom_ao"] as THREE.Texture).colorSpace =
      THREE.LinearSRGBColorSpace;
    (items["ut_startroom_ao"] as THREE.Texture).channel = 1;
    (items["ut_startroom_light"] as THREE.Texture).flipY = false;
    (items["ut_startroom_light"] as THREE.Texture).colorSpace =
      THREE.SRGBColorSpace;
    (items["ut_startroom_light"] as THREE.Texture).channel = 1;
    (items["ut_floor_normal"] as THREE.Texture).flipY = false;
    (items["ut_floor_normal"] as THREE.Texture).colorSpace =
      THREE.LinearSRGBColorSpace;
    (items["ut_floor_normal"] as THREE.Texture).wrapS = THREE.RepeatWrapping;
    (items["ut_floor_normal"] as THREE.Texture).wrapT = THREE.RepeatWrapping;
    (items["ut_floor_roughness"] as THREE.Texture).flipY = false;
    (items["ut_floor_roughness"] as THREE.Texture).colorSpace =
      THREE.LinearSRGBColorSpace;
    (items["ut_floor_roughness"] as THREE.Texture).wrapS = THREE.RepeatWrapping;
    (items["ut_floor_roughness"] as THREE.Texture).wrapT = THREE.RepeatWrapping;

    if (this.base.params.isFurina) {
      (items["decal"] as THREE.Texture).flipY = false;
      (items["decal"] as THREE.Texture).colorSpace = THREE.LinearSRGBColorSpace;
    }
    
    // 配置自定义车身贴图
    if (items["girl"]) {
      (items["girl"] as THREE.Texture).flipY = false;
      (items["girl"] as THREE.Texture).colorSpace = THREE.SRGBColorSpace;
    }
    if (items["girl2"]) {
      (items["girl2"] as THREE.Texture).flipY = false;
      (items["girl2"] as THREE.Texture).colorSpace = THREE.SRGBColorSpace;
    }
  }
  /**
   * 清除所有 GSAP 动画
   * 在切换状态时调用，避免动画冲突
   */
  clearAllTweens() {
    this.t1.clear();
    this.t2.clear();
    this.t3.clear();
    this.t4.clear();
    this.t5.clear();
    this.t6.clear();
    this.t7.clear();
    this.t8.clear();
    this.t9.clear();
  }
  /**
   * 入场动画
   * 从远处飞入，灯光、环境光逐渐亮起
   */
  enter() {
    // 禁用交互（动画期间）
    this.base.params.disableInteract = true;
    
    // ==================== 设置初始状态（全黑） ====================
    this.dynamicEnv.setWeight(0); // 环境权重为 0
    this.startRoom.lightMat.emissive.set(new THREE.Color("#000000")); // 灯光颜色为黑
    this.startRoom.lightMat.emissiveIntensity = 0; // 灯光强度为 0
    this.dynamicEnv.setIntensity(0); // 环境光强度为 0
    this.startRoom.customFloorMat.uniforms.uColor.value.set(
      new THREE.Color("#000000") // 地板颜色为黑
    );
    this.startRoom.customFloorMat.uniforms.uReflectIntensity.value = 0; // 反射强度为 0
    this.furina?.setColor(new THREE.Color("#000000")); // 芙宁娜颜色为黑

    // 隐藏加载屏幕
    document.querySelector(".loader-screen")?.classList.add("hollow");

    // ==================== 动画 1：相机位置 ====================
    this.base.params.isCameraMoving = true; // 标记相机正在移动
    this.t1.to(this.base.params.cameraPos, {
      x: 0,
      y: 0.8,
      z: -7, // 从 Z=-11 移动到 Z=-7
      duration: 4, // 4秒持续时间
      ease: "power2.inOut", // 缓动函数
      onComplete: () => {
        this.base.params.isCameraMoving = false; // 相机停止移动
        this.emit("enter"); // 触发入场完成事件
      },
    });
    // ==================== 动画 2：灯光和颜色 ====================
    const lightColor = new THREE.Color();
    const blackColor = new THREE.Color("#000000");
    const whiteColor = new THREE.Color("#ffffff");
    this.t2.to(this.base.params, {
      lightAlpha: 1, // 灯光透明度从 0 → 1
      lightIntensity: 1, // 灯光强度从 0 → 1
      reflectIntensity: 25, // 反射强度从 0 → 25
      furinaLerpColor: 1, // 芙宁娜颜色混合比例从 0 → 1
      duration: 4, // 4秒持续时间
      delay: 1, // 延迟 1秒开始
      ease: "power2.inOut",
      onUpdate: () => {
        // 每帧更新：混合灯光颜色（黑色 → 白色）
        lightColor
          .copy(blackColor)
          .lerp(whiteColor, this.base.params.lightAlpha);

        // 应用到灯光材质
        this.startRoom.lightMat.emissive.set(lightColor);
        this.startRoom.lightMat.emissiveIntensity =
          this.base.params.lightIntensity;

        // 应用到地板颜色
        this.startRoom.customFloorMat.uniforms.uColor.value.set(lightColor);
        this.startRoom.customFloorMat.uniforms.uReflectIntensity.value =
          this.base.params.reflectIntensity;

        // 应用到芙宁娜颜色
        this.furina?.setColor(lightColor);
      },
    });
    // ==================== 动画 3：环境光 ====================
    this.t3
      .to(this.base.params, {
        envIntensity: 1, // 环境光强度从 0 → 1
        duration: 4,
        delay: 0.5, // 延迟 0.5秒
        ease: "power2.inOut",
        onUpdate: () => {
          this.dynamicEnv.setIntensity(this.base.params.envIntensity);
        },
      })
      .to(
        this.base.params,
        {
          envWeight: 1, // 环境权重从 0 → 1（夜间 → 明亮）
          duration: 4,
          ease: "power2.inOut",
          onUpdate: () => {
            this.dynamicEnv.setWeight(this.base.params.envWeight);
          },
        },
        "-=2.5" // 提前 2.5秒开始（与上个动画重叠）
      );
  }
  /**
   * 直接进入（跳过入场动画）
   * 用于调试时快速进入场景
   */
  enterDirectly() {
    document.querySelector(".loader-screen")?.classList.add("hollow");
    this.base.params.isCameraMoving = false;
    this.base.controls.controls.setPosition(0, 0.8, -7); // 直接设置相机位置
    this.base.params.envIntensity = 1; // 环境光直接设为最大
    this.emit("enter"); // 触发入场完成事件
  }
  /**
   * 加速动画
   * 点击车辆时触发，启动加速特效、相机抖动、Bloom 辉光等
   */
  async rush() {
    // 只有在SU7高亮时才执行加速效果
    if (this.carTimeline.activeIndex !== 0) {
      return;
    }

    // 如果已经在加速中，再次点击则减速
    if (this.base.params.isRushing) {
      this.rushDone();
      return;
    }

    // 如果交互被禁用，直接返回
    if (this.base.params.disableInteract) {
      return;
    }

    // 禁用交互（动画期间）
    this.base.params.disableInteract = true;
    // 清除所有正在进行的动画
    this.clearAllTweens();
    // 初始化颜色对象
    // this.base.controls.controls.setPosition(6.4, 1, -3); // 调试用
    const floorColor = new THREE.Color();
    const blackColor = new THREE.Color("#000000");
    const camera = this.base.camera as THREE.PerspectiveCamera;

    const furinaColor = new THREE.Color();
    const furinaFadeColor = new THREE.Color("#666666"); // 芙宁娜淡化颜色

    // 启动芙宁娜驾驶动画
    this.furina?.drive();

    // ==================== 动画 4：速度 ====================
    this.t4
      .to(this.base.params, {
        speed: 4, // 速度从 0 → 4
        duration: 2,
        ease: "power2.out",
        onComplete: () => {
          this.base.params.isRushing = true; // 标记为加速状态
          this.base.params.disableInteract = false; // 启用交互（允许再次点击减速）
        },
      })
      .to(this.base.params, {
        speed: 10, // 速度从 4 → 10
        duration: 4,
        ease: "power2.out",
      });
    this.t5.to(this.base.params, {
      lightOpacity: 0,
      duration: 1,
      ease: "power2.out",
      onUpdate: () => {
        this.startRoom.lightMat.opacity = this.base.params.lightOpacity;
      },
    });
    this.t6.fromTo(
      this.base.params,
      {
        floorLerpColor: 0,
        furinaLerpColor: 0,
      },
      {
        floorLerpColor: 1,
        furinaLerpColor: 1,
        duration: 4,
        ease: "none",
        onUpdate: () => {
          floorColor.lerp(blackColor, this.base.params.floorLerpColor);
          this.startRoom.customFloorMat.uniforms.uColor.value.set(floorColor);

          furinaColor.lerp(furinaFadeColor, this.base.params.furinaLerpColor);
          this.furina?.setColor(furinaColor);
        },
      }
    );
    this.t7.to(this.base.params, {
      envIntensity: 0.01,
      duration: 1,
      ease: "power2.out",
      onUpdate: () => {
        this.dynamicEnv.setIntensity(this.base.params.envIntensity);
      },
    });
    this.t8.to(this.base.params, {
      speedUpOpacity: 1,
      cameraFov: 36,
      duration: 2,
      ease: "power2.out",
      onUpdate: () => {
        this.speedup.material.uniforms.uOpacity.value =
          this.base.params.speedUpOpacity;

        camera.fov = this.base.params.cameraFov;
        camera.updateProjectionMatrix();
      },
    });
    await kokomi.sleep(1000);
    this.base.scene.environment = this.environment.texture;
    this.t9.to(this.base.params, {
      carBodyEnvIntensity: 10,
      cameraShakeIntensity: 1,
      bloomLuminanceSmoothing: 0.4,
      bloomIntensity: 2,
      duration: 4,
      ease: "power2.out",
      onUpdate: () => {
        this.car.setBodyEnvmapIntensity(this.base.params.carBodyEnvIntensity);
        this.cameraShake.setIntensity(this.base.params.cameraShakeIntensity);
        this.base.post.setLuminanceSmoothing(
          this.base.params.bloomLuminanceSmoothing
        );
        this.base.post.setIntensity(this.base.params.bloomIntensity);
      },
    });
  }
  /**
   * 减速动画
   * 在加速状态下再次点击触发，恢复到静止状态
   */
  rushDone() {
    // 如果交互被禁用，直接返回
    if (this.base.params.disableInteract) {
      return;
    }

    // 禁用交互（动画期间）
    this.base.params.disableInteract = true;
    // 清除所有正在进行的动画
    this.clearAllTweens();
    
    const floorColor = new THREE.Color();
    const whiteColor = new THREE.Color("#ffffff");
    const camera = this.base.camera as THREE.PerspectiveCamera;

    const furinaColor = new THREE.Color();
    const furinaOriginalColor = new THREE.Color("#ffffff"); // 芙宁娜原始颜色

    // 暂停芙宁娜驾驶动画
    this.furina?.pause();

    // ==================== 动画 4：减速 ====================
    this.t4.to(this.base.params, {
      speed: 0, // 速度降为 0
      duration: 2,
      ease: "power2.out",
      onComplete: () => {
        this.base.params.isRushing = false; // 取消加速状态
        this.base.params.disableInteract = false; // 启用交互
      },
    });
    this.t5.to(this.base.params, {
      lightOpacity: 1,
      duration: 1,
      ease: "power2.out",
      onUpdate: () => {
        this.startRoom.lightMat.opacity = this.base.params.lightOpacity;
      },
    });
    this.t6.fromTo(
      this.base.params,
      { floorLerpColor: 0, furinaLerpColor: 0 },
      {
        floorLerpColor: 1,
        furinaLerpColor: 1,
        duration: 4,
        ease: "none",
        onUpdate: () => {
          floorColor.lerp(whiteColor, this.base.params.floorLerpColor);
          this.startRoom.customFloorMat.uniforms.uColor.value.set(floorColor);

          furinaColor.lerp(
            furinaOriginalColor,
            this.base.params.furinaLerpColor
          );
          this.furina?.setColor(furinaColor);
        },
      }
    );
    this.t7.to(this.base.params, {
      envIntensity: 1,
      duration: 1,
      ease: "power2.out",
      onUpdate: () => {
        this.dynamicEnv.setIntensity(this.base.params.envIntensity);
      },
    });
    this.t8.to(this.base.params, {
      speedUpOpacity: 0,
      cameraFov: 33.4,
      duration: 2,
      ease: "power2.out",
      onUpdate: () => {
        this.speedup.material.uniforms.uOpacity.value =
          this.base.params.speedUpOpacity;

        camera.fov = this.base.params.cameraFov;
        camera.updateProjectionMatrix();
      },
    });
    this.t9.to(this.base.params, {
      carBodyEnvIntensity: 1,
      cameraShakeIntensity: 0,
      bloomLuminanceSmoothing: 1.6,
      bloomIntensity: 1,
      duration: 4,
      ease: "power2.out",
      onUpdate: () => {
        this.car.setBodyEnvmapIntensity(this.base.params.carBodyEnvIntensity);
        this.cameraShake.setIntensity(this.base.params.cameraShakeIntensity);
        this.base.post.setLuminanceSmoothing(
          this.base.params.bloomLuminanceSmoothing
        );
        this.base.post.setIntensity(this.base.params.bloomIntensity);
      },
    });
    this.base.scene.environment = this.dynamicEnv.envmap;
  }

  /**
   * 处理时间线切换
   */
  handleTimelineChange(viewId: string) {
    switch (viewId) {
      case "body":
        // 停止车辆旋转动画
        if (this.carRotationTween) {
          this.carRotationTween.kill();
          this.carRotationTween = null;
        }
        
        // 销毁雷达动画
        if (this.radarAnimation) {
          this.radarAnimation.destroy();
          this.radarAnimation = null;
        }
        this.removeRadarMouseEvents();
        
        // 恢复默认相机位置
        this.base.params.isCameraMoving = true;
        gsap.to(this.base.params.cameraPos, {
          x: 0,
          y: 0.8,
          z: -7,
          duration: 1.5,
          ease: "power2.inOut",
          onComplete: () => {
            this.base.params.isCameraMoving = false;
          }
        });
        
        // 切换到车身视图 - 旋转45度并显示尺寸标注
        this.rotateCarToAngle(Math.PI / 1.3);
        this.carDimensions.show();
        // 销毁风阻线条
        if (this.airflowLines) {
          this.airflowLines.destroy();
          this.airflowLines = null;
        }
        // 显示灯光板
        if (this.startRoom.lightBoard) {
          this.startRoom.lightBoard.visible = true;
          const material = this.startRoom.lightBoard.material as THREE.MeshStandardMaterial;
          if (material) {
            material.transparent = true;
            gsap.to(material, {
              opacity: 1,
              duration: 0.5
            });
          }
        }
        // 隐藏传感器列表
        this.hideRadarSensorList();
        // 隐藏定制UI
        this.hideCustomTitle();
        this.hideMaterialControls();
        // 更新标题为外观设计内容
        this.carTitle.updateContent(
          "「外观设计」",
          "优雅与速度感并存经得起时间考验的设计",
          "遵循「符合直觉」的美学设计理念，造就Xiaomi SU7 经典的流畅车身线条。富有力量的车身线条与自然舒展的车身比例，让优雅与速度相得益彰。"
        );
        break;
      case "windResistance":
        // 切换到风阻视图
        this.carDimensions.hide();
        
        // 停止之前的旋转动画
        if (this.carRotationTween) {
          this.carRotationTween.kill();
        }
        
        // 销毁雷达动画
        if (this.radarAnimation) {
          this.radarAnimation.destroy();
          this.radarAnimation = null;
        }
        this.removeRadarMouseEvents();
        
        // 恢复默认相机位置
        this.base.params.isCameraMoving = true;
        gsap.to(this.base.params.cameraPos, {
          x: 0,
          y: 0.8,
          z: -7,
          duration: 1.5,
          ease: "power2.inOut",
          onComplete: () => {
            this.base.params.isCameraMoving = false;
          }
        });
        
        // 显示灯光板
        if (this.startRoom.lightBoard) {
          this.startRoom.lightBoard.visible = true;
          const material = this.startRoom.lightBoard.material as THREE.MeshStandardMaterial;
          if (material) {
            material.transparent = true;
            gsap.to(material, {
              opacity: 1,
              duration: 0.5
            });
          }
        }
        
        // 旋转到20度后停止
        const angleInRadians = (50 * Math.PI) / 180; // 20度转弧度
        this.rotateCarToAngle(angleInRadians);
        
        // 创建并显示风阻线条
        if (!this.airflowLines) {
          const airflowLines = new AirflowLines(this.base);
          this.airflowLines = airflowLines;
          // 将贝塞尔曲线添加到rotationGroup，使其跟随车辆一起旋转
          airflowLines.addExisting(this.rotationGroup);
        }
        this.airflowLines.show();
        
        // 隐藏传感器列表
        this.hideRadarSensorList();
        // 隐藏定制UI
        this.hideCustomTitle();
        this.hideMaterialControls();
        
        // 更新标题为风阻内容
        this.carTitle.updateContent(
          "出色的超低风阻系数",
          "风，就是最好的设计师。",
          "经过1000次以上仿真实验和超过300次油泥模型调整，不断寻找风速、车身曲线的最优解。\n最终达成Cd0.195超低风阻系数，带来难以想象的低能耗和出色续航表现。",
          "Cd 0.195"
        );
        break;
      case "radar":
        // 停止车辆旋转动画
        if (this.carRotationTween) {
          this.carRotationTween.kill();
          this.carRotationTween = null;
        }
        
        // 切换到雷达视图 - 车辆从右向左旋转60度
        const radarAngle = (90 * Math.PI) / 180;
        this.rotateCarToAngle(radarAngle);
        this.carDimensions.hide();
        
        // 销毁风阻线条
        if (this.airflowLines) {
          this.airflowLines.destroy();
          this.airflowLines = null;
        }
        
        // 隐藏灯光板
        if (this.startRoom.lightBoard) {
          const material = this.startRoom.lightBoard.material as THREE.MeshStandardMaterial;
          if (material) {
            material.transparent = true;
            gsap.to(material, {
              opacity: 0,
              duration: 0.5,
              onComplete: () => {
                this.startRoom.lightBoard.visible = false;
              }
            });
          }
        }
        
        // 设置俯视视角（从上往下看）
        this.base.params.isCameraMoving = true;
        gsap.to(this.base.params.cameraPos, {
          x: 0,
          y: 17, // 相机高度（提高到12）
          z: 0.5, // 略微偏后
          duration: 1.5,
          ease: "power2.inOut",
          onComplete: () => {
            this.base.params.isCameraMoving = false;
          }
        });
        
        // 显示传感器列表
        this.showRadarSensorList();
        
        // 隐藏定制UI
        this.hideCustomTitle();
        this.hideMaterialControls();
        
        // 更新标题为智能驾驶内容
        this.carTitle.updateContent(
          "「智能驾驶」",
          "隆重介绍XiaomiPilot更聪明、更安全的智能驾驶系统",
          "搭载两颗 NVIDIA DRIVE Orin 芯片，综合算力高达 508 TOPS，感知硬件具备全贵的大范围探测能力；\n在此之上，以领先行业的智能驾驶算法深度赋能小米全栈自研的全场景智能辅助驾驶。"
        );
        
        // 创建雷达动画
        if (!this.radarAnimation) {
          const radarAnimation = new RadarAnimation(this.base);
          this.radarAnimation = radarAnimation;
          radarAnimation.addExisting();
        }
        
        // 设置鼠标按下/松开事件监听（用于触发动画）
        this.setupRadarMouseEvents();
        break;
      case "custom":
        // 停止车辆旋转动画
        if (this.carRotationTween) {
          this.carRotationTween.kill();
          this.carRotationTween = null;
        }
        
        // 销毁雷达动画
        if (this.radarAnimation) {
          this.radarAnimation.destroy();
          this.radarAnimation = null;
        }
        this.removeRadarMouseEvents();
        
        // 切换到定制视图 - 车辆从左到右旋转90度
        const customAngle = (125 * Math.PI) / 180;
        this.rotateCarToAngle(customAngle);
        this.carDimensions.hide();
        
        // 销毁风阻线条
        if (this.airflowLines) {
          this.airflowLines.destroy();
          this.airflowLines = null;
        }
        
        // 隐藏灯光板
        if (this.startRoom.lightBoard) {
          const material = this.startRoom.lightBoard.material as THREE.MeshStandardMaterial;
          if (material) {
            material.transparent = true;
            gsap.to(material, {
              opacity: 0,
              duration: 0.5,
              onComplete: () => {
                this.startRoom.lightBoard.visible = false;
              }
            });
          }
        }
        
        // 隐藏传感器列表
        this.hideRadarSensorList();
        
        // 恢复默认相机位置
        this.base.params.isCameraMoving = true;
        gsap.to(this.base.params.cameraPos, {
          x: 0,
          y: 0.8,
          z: -7,
          duration: 1.5,
          ease: "power2.inOut",
          onComplete: () => {
            this.base.params.isCameraMoving = false;
          }
        });
        
        // 隐藏标题
        this.carTitle.updateContent("", "", "");
        
        // 显示左上角SU7大字
        this.showCustomTitle();
        
        // 显示材质调节滑块
        this.showMaterialControls();
        
        // 延迟初始化滑块值，确保DOM已渲染
        setTimeout(() => {
          this.initializeMaterialControls();
        }, 100);
        break;
      default:
        // 停止车辆旋转动画
        if (this.carRotationTween) {
          this.carRotationTween.kill();
          this.carRotationTween = null;
        }
        
        // 销毁雷达动画
        if (this.radarAnimation) {
          this.radarAnimation.destroy();
          this.radarAnimation = null;
        }
        this.removeRadarMouseEvents();
        
        // 其他视图 - 恢复默认角度并隐藏尺寸标注
        this.rotateCarToAngle(0);
        this.carDimensions.hide();
        // 停止波浪线动画（如果正在播放）
        this.carWaveLines.stop();
        // 销毁风阻线条
        if (this.airflowLines) {
          this.airflowLines.destroy();
          this.airflowLines = null;
        }
        // 显示灯光板
        if (this.startRoom.lightBoard) {
          this.startRoom.lightBoard.visible = true;
          const material = this.startRoom.lightBoard.material as THREE.MeshStandardMaterial;
          if (material) {
            material.transparent = true;
            gsap.to(material, {
              opacity: 1,
              duration: 0.5
            });
          }
        }
        // 隐藏传感器列表
        this.hideRadarSensorList();
        // 隐藏定制UI
        this.hideCustomTitle();
        this.hideMaterialControls();
        // 恢复默认相机位置
        this.base.params.isCameraMoving = true;
        gsap.to(this.base.params.cameraPos, {
          x: 0,
          y: 0.8,
          z: -7,
          duration: 1.5,
          ease: "power2.inOut",
          onComplete: () => {
            this.base.params.isCameraMoving = false;
          }
        });
        // 恢复默认标题
        this.carTitle.resetContent();
        break;
    }
  }

  /**
   * 旋转整体（车辆、灯光板和地面作为一个组）
   */
  rotateCarToAngle(angle: number) {
    // 旋转整个旋转组
    gsap.to(this.rotationGroup.rotation, {
      y: angle,
      duration: 1.5,
      ease: "power2.inOut",
    });
  }

  /**
   * 显示雷达传感器列表
   */
  showRadarSensorList() {
    // 检查是否已存在
    let sensorList = document.querySelector('.radar-sensor-list') as HTMLElement;
    
    if (!sensorList) {
      // 创建传感器列表容器
      sensorList = document.createElement('div');
      sensorList.className = 'radar-sensor-list';
      sensorList.innerHTML = `
        <div class="sensor-item">
          <span class="sensor-name">激光雷达</span>
          <span class="sensor-count">×1</span>
        </div>
        <div class="sensor-item">
          <span class="sensor-name">高清摄像头</span>
          <span class="sensor-count">×11</span>
        </div>
        <div class="sensor-item">
          <span class="sensor-name">毫米波雷达</span>
          <span class="sensor-count">×3</span>
        </div>
        <div class="sensor-item">
          <span class="sensor-name">超声波雷达</span>
          <span class="sensor-count">×12</span>
        </div>
      `;
      document.body.appendChild(sensorList);
    }
    
    // 显示动画
    gsap.to(sensorList, {
      opacity: 1,
      x: 50, // 从左侧滑入
      duration: 0.5,
      ease: "power2.out"
    });
  }

  /**
   * 临时隐藏雷达传感器列表（不销毁DOM）
   */
  hideRadarSensorListTemporary() {
    const sensorList = document.querySelector('.radar-sensor-list') as HTMLElement;
    if (sensorList) {
      gsap.to(sensorList, {
        opacity: 0,
        x: -50,
        duration: 0.3,
        ease: "power2.in"
      });
    }
  }

  /**
   * 隐藏并销毁雷达传感器列表
   */
  hideRadarSensorList() {
    const sensorList = document.querySelector('.radar-sensor-list') as HTMLElement;
    if (sensorList) {
      gsap.to(sensorList, {
        opacity: 0,
        x: -50,
        duration: 0.3,
        ease: "power2.in",
        onComplete: () => {
          // 动画完成后销毁DOM元素
          sensorList.remove();
        }
      });
    }
  }

  /**
   * 显示左上角SU7大字
   */
  showCustomTitle() {
    let customTitle = document.querySelector('.custom-su7-title') as HTMLElement;
    
    if (!customTitle) {
      customTitle = document.createElement('div');
      customTitle.className = 'custom-su7-title';
      customTitle.textContent = 'SU7';
      document.body.appendChild(customTitle);
    }
    
    gsap.to(customTitle, {
      opacity: 1,
      duration: 0.5,
      ease: "power2.out"
    });
  }

  /**
   * 隐藏左上角SU7大字
   */
  hideCustomTitle() {
    const customTitle = document.querySelector('.custom-su7-title') as HTMLElement;
    if (customTitle) {
      gsap.to(customTitle, {
        opacity: 0,
        duration: 0.3,
        ease: "power2.in"
      });
    }
  }

  /**
   * 显示材质调节滑块
   */
  showMaterialControls() {
    let controls = document.querySelector('.material-controls') as HTMLElement;
    
    if (!controls) {
      controls = document.createElement('div');
      controls.className = 'material-controls';
      controls.innerHTML = `
        <div class="control-item">
          <span class="control-label">色相</span>
          <input type="range" class="control-slider color-slider hue-slider" min="0" max="360" value="180" />
        </div>
        <div class="control-item">
          <span class="control-label">饱和度</span>
          <input type="range" class="control-slider saturation-slider" min="0" max="100" value="80" />
        </div>
        <div class="control-item">
          <span class="control-label">明度</span>
          <input type="range" class="control-slider lightness-slider" min="0" max="100" value="50" />
        </div>
        <div class="control-item">
          <span class="control-label">金属度</span>
          <input type="range" class="control-slider metalness-slider" min="0" max="100" value="80" />
        </div>
        <div class="control-item">
          <span class="control-label">粗糙度</span>
          <input type="range" class="control-slider roughness-slider" min="0" max="100" value="30" />
        </div>
      `;
      document.body.appendChild(controls);
      
      // 添加滑块事件监听器
      this.bindMaterialControls();
    }
    
    gsap.to(controls, {
      opacity: 1,
      x: 0,
      duration: 0.5,
      ease: "power2.out"
    });
  }

  /**
   * 绑定材质调节滑块事件
   */
  bindMaterialControls() {
    const hueSlider = document.querySelector('.hue-slider') as HTMLInputElement;
    const saturationSlider = document.querySelector('.saturation-slider') as HTMLInputElement;
    const lightnessSlider = document.querySelector('.lightness-slider') as HTMLInputElement;
    const metalnessSlider = document.querySelector('.metalness-slider') as HTMLInputElement;
    const roughnessSlider = document.querySelector('.roughness-slider') as HTMLInputElement;
    
    // 色相滑块
    if (hueSlider) {
      hueSlider.addEventListener('input', (e) => {
        const hue = parseInt((e.target as HTMLInputElement).value);
        const saturation = parseInt(saturationSlider.value);
        const lightness = parseInt(lightnessSlider.value);
        this.updateCarColor(hue, saturation, lightness);
      });
    }
    
    // 饱和度滑块
    if (saturationSlider) {
      saturationSlider.addEventListener('input', (e) => {
        const hue = parseInt(hueSlider.value);
        const saturation = parseInt((e.target as HTMLInputElement).value);
        const lightness = parseInt(lightnessSlider.value);
        this.updateCarColor(hue, saturation, lightness);
      });
    }
    
    // 明度滑块
    if (lightnessSlider) {
      lightnessSlider.addEventListener('input', (e) => {
        const hue = parseInt(hueSlider.value);
        const saturation = parseInt(saturationSlider.value);
        const lightness = parseInt((e.target as HTMLInputElement).value);
        this.updateCarColor(hue, saturation, lightness);
      });
    }
    
    // 金属度滑块
    if (metalnessSlider) {
      metalnessSlider.addEventListener('input', (e) => {
        const metalness = parseInt((e.target as HTMLInputElement).value) / 100;
        if (this.car && this.car.bodyMat) {
          this.car.bodyMat.metalness = metalness;
        }
      });
    }
    
    // 粗糙度滑块
    if (roughnessSlider) {
      roughnessSlider.addEventListener('input', (e) => {
        const roughness = parseInt((e.target as HTMLInputElement).value) / 100;
        if (this.car && this.car.bodyMat) {
          this.car.bodyMat.roughness = roughness;
        }
      });
    }
  }

  /**
   * 更新车辆颜色（基于HSL）
   */
  updateCarColor(hue: number, saturation: number, lightness: number) {
    if (this.car && this.car.bodyMat) {
      // 将HSL转换为RGB，然后设置颜色
      const color = new THREE.Color();
      color.setHSL(hue / 360, saturation / 100, lightness / 100);
      this.car.bodyMat.color = color;
    }
  }

  /**
   * 初始化材质控制滑块的值
   */
  initializeMaterialControls() {
    if (!this.car || !this.car.bodyMat) return;
    
    // 获取当前车辆颜色的HSL值
    const hsl = { h: 0, s: 0, l: 0 };
    this.car.bodyMat.color.getHSL(hsl);
    
    // 设置滑块值
    const hueSlider = document.querySelector('.hue-slider') as HTMLInputElement;
    const saturationSlider = document.querySelector('.saturation-slider') as HTMLInputElement;
    const lightnessSlider = document.querySelector('.lightness-slider') as HTMLInputElement;
    const metalnessSlider = document.querySelector('.metalness-slider') as HTMLInputElement;
    const roughnessSlider = document.querySelector('.roughness-slider') as HTMLInputElement;
    
    if (hueSlider) hueSlider.value = Math.round(hsl.h * 360).toString();
    if (saturationSlider) saturationSlider.value = Math.round(hsl.s * 100).toString();
    if (lightnessSlider) lightnessSlider.value = Math.round(hsl.l * 100).toString();
    if (metalnessSlider) metalnessSlider.value = Math.round(this.car.bodyMat.metalness * 100).toString();
    if (roughnessSlider) roughnessSlider.value = Math.round(this.car.bodyMat.roughness * 100).toString();
  }

  /**
   * 隐藏材质调节滑块
   */
  hideMaterialControls() {
    const controls = document.querySelector('.material-controls') as HTMLElement;
    if (controls) {
      gsap.to(controls, {
        opacity: 0,
        x: -50,
        duration: 0.3,
        ease: "power2.in"
      });
    }
  }

  /**
   * 创建音乐控制按钮
   */
  createMusicControl() {
    // 创建按钮容器
    const musicBtn = document.createElement("div");
    musicBtn.className = "music-control";
    musicBtn.innerHTML = `
      <svg class="music-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M9 18V5l12-2v13"></path>
        <circle cx="6" cy="18" r="3"></circle>
        <circle cx="18" cy="16" r="3"></circle>
      </svg>
    `;
    
    // 添加到页面
    document.body.appendChild(musicBtn);
    
    // 音乐播放状态
    let isPlaying = true;
    
    // 点击事件
    musicBtn.addEventListener("click", () => {
      if (isPlaying) {
        this.bgm.pause();
        musicBtn.classList.add("paused");
      } else {
        this.bgm.play();
        musicBtn.classList.remove("paused");
      }
      isPlaying = !isPlaying;
    });
  }

  /**
   * 设置雷达视图的鼠标事件监听
   */
  setupRadarMouseEvents() {
    // 移除之前的事件监听（如果有）
    this.removeRadarMouseEvents();

    // 鼠标按下事件
    const onMouseDown = () => {
      if (this.carTimeline.activeIndex !== 3) return; // 只在雷达视图响应（index 3 是雷达）
      this.startRadarAnimation();
    };

    // 鼠标松开事件
    const onMouseUp = () => {
      if (this.carTimeline.activeIndex !== 3) return;
      this.stopRadarAnimation();
    };

    // 鼠标离开事件
    const onMouseLeave = () => {
      if (this.carTimeline.activeIndex !== 3) return;
      this.stopRadarAnimation();
    };

    // 保存事件引用供后续移除
    (this as any)._radarMouseDown = onMouseDown;
    (this as any)._radarMouseUp = onMouseUp;
    (this as any)._radarMouseLeave = onMouseLeave;

    // 绑定事件
    window.addEventListener('mousedown', onMouseDown);
    window.addEventListener('mouseup', onMouseUp);
    window.addEventListener('mouseleave', onMouseLeave);
    
    // 触摸事件支持
    window.addEventListener('touchstart', onMouseDown);
    window.addEventListener('touchend', onMouseUp);
  }

  /**
   * 移除雷达视图的鼠标事件监听
   */
  removeRadarMouseEvents() {
    if ((this as any)._radarMouseDown) {
      window.removeEventListener('mousedown', (this as any)._radarMouseDown);
      window.removeEventListener('mouseup', (this as any)._radarMouseUp);
      window.removeEventListener('mouseleave', (this as any)._radarMouseLeave);
      window.removeEventListener('touchstart', (this as any)._radarMouseDown);
      window.removeEventListener('touchend', (this as any)._radarMouseUp);
      
      delete (this as any)._radarMouseDown;
      delete (this as any)._radarMouseUp;
      delete (this as any)._radarMouseLeave;
    }
  }

  /**
   * 启动雷达动画
   */
  startRadarAnimation() {
    if (this.isRadarPressed) return;
    this.isRadarPressed = true;

    // 临时隐藏传感器列表和标题（不销毁DOM）
    this.hideRadarSensorListTemporary();
    this.carTitle.hide();

    // 启动雷达动画
    if (this.radarAnimation) {
      this.radarAnimation.start();
    }
  }

  /**
   * 停止雷达动画
   */
  stopRadarAnimation() {
    if (!this.isRadarPressed) return;
    this.isRadarPressed = false;

    // 显示传感器列表和标题
    this.showRadarSensorList();
    this.carTitle.show();

    // 停止雷达动画
    if (this.radarAnimation) {
      this.radarAnimation.stop();
    }
  }
}
